package com.cj.mobile.iabp.mvp.ui.activity;

import static com.jess.arms.utils.Preconditions.checkNotNull;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.di.component.DaggerHomeSearchComponent;
import com.cj.mobile.iabp.mvp.contract.HomeSearchContract;
import com.cj.mobile.iabp.mvp.model.entity.PatientInfo;
import com.cj.mobile.iabp.mvp.presenter.HomeSearchPresenter;
import com.cj.mobile.iabp.mvp.ui.adapter.SearchInfoAdapter;
import com.google.android.flexbox.FlexboxLayout;
import com.jakewharton.rxbinding3.widget.RxTextView;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created on 2025/08/31 20:27
 *
 * @author Love_xie
 * module name is HomeSearchActivity
 */
public class HomeSearchActivity extends BaseActivity<HomeSearchPresenter> implements HomeSearchContract.View, DefaultAdapter.OnRecyclerViewItemClickListener {

    /*----------------------------------------------------------------控件信息----------------------------------------------------------------*/
    @BindView(R.id.edit_homesearch_input)
    EditText editInput;                                                                             // 输入内容

    @BindView(R.id.imvi_homesearch_clear)
    ImageView imviClear;                                                                             // 清除内容

    @BindView(R.id.imvi_homesearch_del)
    ImageView imviDel;                                                                              // 删除历史记录

    @BindView(R.id.flla_homesearch_history)
    FlexboxLayout fllaHistory;                                                                       // 历史记录

    @BindView(R.id.revi_homesearch_result)
    RecyclerView mRecyclerView;                                                                        // 搜索结果

    @BindView(R.id.lila_homesearch_notdata)
    View notData;
    /*----------------------------------------------------------------业务信息----------------------------------------------------------------*/

    // 是否初始化edit
    private boolean isInit;

    @Inject
    RecyclerView.LayoutManager mLayoutManager;

    @Inject
    SearchInfoAdapter mAdapter;


    /**
     * 根据主题使用不同的颜色。
     * 如果想要纯透明，则需要重写此方法，返回值为 -1 即可。
     */
    public int useStatusBarColor() {
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(android.R.color.white, typedValue, true);
        return typedValue.data;
    }

    /**
     * 将状态栏改为浅色模式(状态栏 icon 和字体会变成深色)
     */
    public boolean useLightStatusBar() {
        return true;
    }

    @Override
    public void onDestroy() {
        // super.onDestroy()之后会unbind,所有view被置为null,所以必须在之前调用
        DefaultAdapter.releaseAllHolder(mRecyclerView);
        KeyboardUtils.unregisterSoftInputChangedListener(getWindow());
        super.onDestroy();

        this.mLayoutManager = null;
        this.mAdapter = null;

    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHomeSearchComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_home_search;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        // 设置标题
        setTitle("搜索");

        initEdit();

        // 初始化RecyclerView
        initRecyclerView();

        if (mPresenter != null)
            mPresenter.initData();
    }

    @SuppressLint("CheckResult")
    private void initEdit() {
        RxTextView.textChanges(editInput)
                .debounce(800, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(charSequence -> {
                    if (isInit) {
                        String val = charSequence.toString();
                        if (!TextUtils.isEmpty(val)) {
                            imviClear.setVisibility(View.VISIBLE);

                            hideInput();
                            if (mPresenter != null) {
                                mPresenter.searchContent(val);
                            }
                        } else {
                            imviClear.setVisibility(View.GONE);
                        }
                    } else {
                        isInit = true;
                    }

                });
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
    }

    @OnClick({
            R.id.imvi_homesearch_clear,                                                             // 清除输入框
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imvi_homesearch_clear:                                                        // 清除输入框
                // 清除输入框
                editInput.setText("");
                // 隐藏结果布局
                mRecyclerView.setVisibility(View.GONE);
                // 隐藏无数据
                notData.setVisibility(View.GONE);
                // 刷新历史记录
                if (mPresenter != null) {
                    mPresenter.initData();
                }
                break;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        hideInput();
        return super.onTouchEvent(event);
    }

    /**
     * 隐藏软键盘
     */
    private void hideInput() {
        KeyboardUtils.hideSoftInput(this);
    }

    public Activity getActivity() {
        return this;
    }


    @Override
    public void showLoading() {
        // 隐藏“暂无搜索结果”
        if (notData != null)
            notData.setVisibility(View.GONE);

        if (mRecyclerView != null)
            mRecyclerView.setVisibility(View.GONE);
    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void isNotInfo(boolean isValue) {
        if (isValue) {
            if (notData != null)
                notData.setVisibility(View.VISIBLE);

            if (mRecyclerView != null)
                mRecyclerView.setVisibility(View.GONE);
        } else {
            if (notData != null)
                notData.setVisibility(View.GONE);

            if (mRecyclerView != null)
                mRecyclerView.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void addSearchHistory(List<String> list) {
        if (!list.isEmpty()) {
            fllaHistory.removeAllViews();

            for (String item : list) {
                TextView textView = new TextView(this);
                // 3. 设置 TextView 宽高（关键：根据需求调整，这里用 wrap_content）
                LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,  // 宽：包裹内容
                        ViewGroup.LayoutParams.WRAP_CONTENT   // 高：包裹内容
                );

                tvParams.leftMargin = 10;
                tvParams.rightMargin = 10;
                tvParams.topMargin = 8;
                tvParams.bottomMargin = 8;
                textView.setLayoutParams(tvParams);
                textView.setPadding(15, 10, 15, 10);

                textView.setText(item);
                textView.setTextColor(getResources().getColor(R.color.bg_black));
                textView.setBackgroundResource(R.color.home_search_bg_color);
                textView.setOnClickListener(v -> {
                    editInput.setText(textView.getText().toString());
                });

                fllaHistory.addView(textView);
            }
        }

    }

    @Override
    public void onItemClick(@NonNull View view, int viewType, @NonNull Object data, int position) {
        PatientInfo info = (PatientInfo) data;

        Bundle mBundle = new Bundle();
        mBundle.putString("id", info.getId());
        ActivityUtils.startActivity(mBundle, PatientInfoActivity.class);
    }
}